<?php


namespace app\common\model;


use think\Db;

class Products extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_products';
    // 主键ID
    protected $pk = 'product_id';

    //审核商品类型
    public static $classlist = [
        '1'=>'普通商品',
        '2'=>'兑换商品',
        '3'=>'爱心餐品',
        '4'=>'团餐商品',
    ];

    /**
     * @param array $where  // 查询的条件
     * @param string $item  // 查询的参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*')
    {
        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

    function get_list($cond, $orderby, $item)
    {

        $where = null;

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }

        if(is_numeric($cond['utype'])){
            $where[] = ['utype', '=', $cond['utype']];
        }
        if(!empty($cond['type'])){
            $where[] = ['type', '=', $cond['type']];
        }
        if(!empty($cond['spf_id'])){
            $where[] = ['spf_id', '=', $cond['spf_id']];
        }

        if(!empty($cond['shopid'])){
            $where[] = ['shopid', '=', $cond['shopid']];
        }

        if(!empty($cond['state'])){
            $where[] = ['state', '=', $cond['state']];
        }

        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }


    function get_list_resule($cond, $orderby, $item, $limit = 10, $page = 1, $type = 1)
    {
        $where = null;

        if(!empty($cond['product_name'])){
            $where[] = ['product_name', 'like', "%".$cond['product_name']."%"];
        }
        if(!empty($cond['type_id'])){
            $where[] = ['type_id', '=', $cond['type_id']];
        }
        if(!empty($cond['shop_id'])){
            $where[] = ['shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['state'])){
            $where[] = ['state', '=', $cond['state']];
        }

        if(!empty($cond['approved'])){
            $where[] = ['approved', '=', $cond['approved']];
        }
        if(!empty($cond['show'])){
            $where[] = ['show', '=', $cond['show']];
        }

        $where[] = ['is_del','=',1];

//        var_dump($item);
//        var_dump($where);die;
//        var_dump($orderby);
//        var_dump($page);
//        var_dump($limit);
//        var_dump($type);die;

        $rs = Db::table($this->table)
            ->field($item)
            ->where($where)
            ->order($orderby);
        if($type > 1){
            $rs = $rs->page($page, $limit);
        }

            $rs = $rs->select();
        return $rs;
    }




    function admin_get_list($cond, $orderby, $item = '*',$limit)
    {

        $where = null;

        if(!empty($cond['user_id'])){
            $where[] = ['user_id','=', $cond['user_id']];
        }

        if(!empty($cond['type'])){
            $where[] = ['type', '=', $cond['type']];
        }

        if(!empty($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }

        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }

        if(!empty($cond['shop_name'])){
            $where[] = ['s.shop_name','like',"%".$cond['shop_name']."%"];
        }

        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_shops s','s.shop_id = p.shop_id')
            ->leftjoin('ddt_products_type pt','pt.type_id = p.type_id')
            ->where($where)
            ->field($item)
            ->order('p.product_id desc')
            ->paginate($limit);
        return $rs;
    }

    // 获取分页列表
    function get_list_page($cond,$orderby,$item,$limit)
    {
        $where = null;
//        if(!empty($cond['group_name'])){
//            $where[] = ['group_name','like',"%".$cond['group_name']."%"];
//        }

        // 审核状态
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }

        if(!empty($cond['class_id'])){
            $where[] = ['p.class_id', '=', $cond['class_id']];
        }

        $rs = Db::table($this->table)
            ->alias('p')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->leftJoin('ddt_products_type t','p.type_id = t.type_id')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);

        return $rs;
    }

    //新增、编辑(后台操作)
    function editstatus($params, $id=0){
        $product = $this->getOne(array('id'=>$id));
        if($product['utype'] == '4' && $product['is_produce'] == '1'){
            if($product['approved'] != '1'){$this->setError(-1,'商品审核未通过');return false;}
        }
        // 更新条件
        $where = ['id' => $id];
        $rs = $this->allowField(true)->save($params, $where);
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ['product_id' => $id];
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            $params['createat'] = time();
            // 更新数据
            $this->allowField(true)->save($params);
            $rs = $this->{$this->pk};
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

	function GetProductsList($cond,$orderby){
		$field = "id,type,utype,shopid,name,sidedish,remark,price,mprice,weight,isdiscount,salecount,menuimage,manufacturedate,qualityperiod,stocknum,issprice";
		$where = null;

		if(!empty($cond['utype']) && is_numeric($cond['utype'])){
			$where[] = ['utype', '=', $cond['utype']];
			$where2[] = ['utype', '=', $cond['utype']];
		}
		if(!empty($cond['type']) && is_numeric($cond['type'])){
			$where[] = ['type', '=', $cond['type']];
			$where2[] = ['type', '=', $cond['type']];
		}
		if($cond['isstock'] == true){
			$where[] = ['stocknum','>','0'];
//            $where2[] = ['stocknum','<=','0'];
			$orwhere[] = ['stocknum','<=','0'];
		}

		if(!empty($cond['shopid'])){
			$where[] = ['shopid', '=', $cond['shopid']];
			$where2[] = ['shopid', '=', $cond['shopid']];
		}

		if(!empty($cond['state']) && is_numeric($cond['state'])){
			$where[] = ['state', '=', $cond['state']];
			$where2[] = ['state', '=', $cond['state']];
		}
		$orwhere[] = ['qualityperiod','<',date('Y-m-d',time())];
		$update = [
			'state' => $cond['state'],
		];
		$this->edit2($update,$where2,$orwhere);
		$rs = Db::table($this->table)
			->field($field)
			->where($where)
			->order($orderby)
			->select();
		return $rs;
	}

	function ProductsChecked($cond){
		$field = "id,type,utype,shopid,name,sidedish,remark,price,weight,isdiscount,mprice,salecount,menuimage,manufacturedate,qualityperiod";
		$where = null;

		if(is_numeric($cond['utype'])){
			$where[] = ['utype', '=', $cond['utype']];
		}
		if(!empty($cond['isstock'] && $cond['isstock'] == true)){
			$where[] = ['stocknum','>','0'];
		}

		if(!empty($cond['shopid'])){
			$where[] = ['shopid', '=', $cond['shopid']];
		}

		if(!empty($cond['prodids'] && is_array($cond['prodids']))){
			$ids = [];
			foreach($cond['prodids'] as $key => $value){
				$ids[$key] = $value['good_id'];
			}
			$where[] = ['id', 'in' , $ids];
		}

		if(!empty($cond['state'])){
			$where[] = ['state', '=', $cond['state']];
		}
		$rs = Db::table($this->table)
			->field($field)
			->where($where)
			->select();
		return $rs;
	}

	//    增加商铺浏览次数
	function addvisit($userid,$shopid){
		$gethistory = Db::table('ddt_visittimes')
			->where('userid',$userid)
			->where('shopid',$shopid)
			->find();
		if($gethistory){
			$rs = Db::table('ddt_visittimes')
				->where('userid',$userid)
				->where('shopid',$shopid)
				->setInc('times');
		} else {
			$rs = Db::table('ddt_visittimes')->insert(['userid'=>$userid,'shopid'=>$shopid,'times'=>1]);
		}
		return $rs;
	}


    // 商品增加销量
    function addsalecount($where){
        $rs = $this
            ->where($where)
            ->setInc('salecount');
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

	// 批量审核通过
    function ProductsAdopt($ids)
    {
        $ExamineModel = new ProductExamine();

        // 开启事务
        $this->startTrans();

        $rs = $rs1 = true;
        try{
            // 原生更新
            $rs = $this->execute("UPDATE ddt_products SET approved = 2 WHERE product_id in (".$ids.")");

            $arr = explode(",", $ids);
            $param = [];
            $i = 0;
            foreach ($arr as $key){
                $param[$i]['type'] = 1;
                $param[$i]['product_service_id'] = $key;
                $param[$i]['is_check'] = 2;
                $i += 1;
            }

            $ExamineModel->saveAll($param);

            if($rs === false || $rs1 === false){
                $this->rollback();
                $this->setError(-1,'错误');
                return false;
            }

            $this->commit();
            return true;
        }catch (\Exception $e){
            $this->rollback();
            $this->setError(-1, $e->getMessage());
            return false;
        }
    }


//    h5获取商品列表
    function get_product_list($cond, $orderby, $item = 'p.*',$limit)
    {
        $where = null;
        if(!empty($cond['product_name'])){
            $where[] = ['p.product_name', 'like', '%'.$cond['product_name'].'%'];
        }
        if(!empty($cond['type_id'])){
            $where[] = ['p.type_id', '=', $cond['type_id']];
        }
        if(!empty($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['is_online'])){
            $where[] = ['p.is_online', '=', $cond['is_online']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }

        $rs = $this
            ->alias('p')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);
        return $rs;
    }

//    h5获取每周热门商品列表
//    function get_hot_list($cond, $orderby, $item = 'p.*',$limit,$is_hot = false)
    function get_hot_list($cond, $item = 'p.*',$limit)
    {
        $where = null;
        if(!empty($cond['shop_id'])){
            $where[] = ['p.shop_id', '=', $cond['shop_id']];
        }
        if(!empty($cond['approved'])){
            $where[] = ['p.approved', '=', $cond['approved']];
        }
        if(!empty($cond['state'])){
            $where[] = ['p.state', '=', $cond['state']];
        }
        if(!empty($cond['is_online'])){
            $where[] = ['p.is_online', '=', $cond['is_online']];
        }
        if(!empty($cond['is_del'])){
            $where[] = ['p.is_del', '=', $cond['is_del']];
        }

//        if($is_hot){
            $sdefaultDate = date("Y-m-d");
            //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
            $first=1;
            //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
            $w=date('w',strtotime($sdefaultDate));
            //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
//            $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
            $week_start=strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days');
            //本周结束日期
            $week_end=strtotime(date('Y-m-d',$week_start)." +7 days");
//            var_dump($w);
//            var_dump($week_end);die;
//            var_dump($week_start);die;
            $item .= ",(select sum(quantity) as sales from ddt_orderdetail od join ddt_order o on od.order_id = o.order_id where o.order_status = 4 and od.product_id = p.product_id and o.order_time between ".$week_start." and ".$week_end.") as totalsales";
            $orderby["totalsales"] = "desc";
//        }

        $rs = $this
            ->alias('p')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);
//        echo $this->getLastSql();die;
        return $rs;
    }


//    h5获取商品详情
    function get_product_detail($productid)
    {
        $where = [
            ['product_id', '=', $productid],
            ['approved', '=', 2],
            ['state', '=', 1],
            ['is_online', '=', 1],
            ['is_del', '=', 1]
        ];

        $rs = $this
            ->field('*')
            ->where($where)
            ->find();
        $data = null;
        if(!empty($rs)){
            $data = $rs->toArray();
            $shopModel = new Shops();
            $shop = $shopModel
                ->where([
                    ['shop_id','=',$data['shop_id']],
                    ['approved','=',1],
                    ['state','=',1],
                    ['shop_type','in',[1,3]]
                ])
                ->find();
            $data['shop'] = empty($shop)?null:$shop->toArray();
            $stockModel = new ProductStock();
            $stocks = $stockModel
                ->where([
                    'product_id' => $productid,
                    'is_del' => 1
                ])
                ->select();
            $data['stocks'] = $stocks->toArray();
            $imageModel = new ProductImage();
            $images = $imageModel
                ->where([
                    'product_id' => $productid,
                    'is_show' => 1
                ])
                ->order("sort asc")
                ->select();
//            var_dump($images->toArray());die;
            $data['images'] = $images->toArray();
        }
        return $data;
    }


//    校验非普通商品
    function check_uncommon_product($product_id,$stock_id,$item = 'p.*')
    {
        $where = [
            ['p.product_id','=',$product_id],
            ['p.approved', '=', 2],
            ['p.state', '=', 1],
            ['p.is_del', '=', 1],
            ['p.show','=',4],
            ['ps.is_del','=',1],
            ['ps.p_s_id','=',$stock_id],
            ['s.approved','=',1],
            ['s.state','=',1],
        ];


        $rs = $this
            ->alias('p')
            ->leftJoin('ddt_products_stock ps','ps.product_id = p.product_id')
            ->leftJoin('ddt_shops s','p.shop_id = s.shop_id')
            ->where($where)
            ->field($item)
            ->find();
        if(!$rs){
            $this->setError(-1,"商品或者店铺已下架");
            return false;
        }
        return $rs->toArray();
    }

//     批发商商品入库
    public function warehousing($purchase,$admin)
    {
        $pwhere = [
            ['shop_id','=',$purchase['shop_id']],
            ['source_id','=',$purchase['product_id']],
        ];
        $product = $this->where($pwhere)->find();
        $this->startTrans();
        $stocks = json_decode($purchase['stock_info'],true);
        $stockModel = new ProductStock();
        if(!$product){
            $param = $this->where("product_id","=",$purchase['product_id'])->find()->toArray();
            $param['source_id'] = $purchase['product_id'];
            $param['shop_id'] = $purchase['shop_id'];
            $param['admin_id'] = $admin['user_id'];
            unset($param['product_id'],$param['salecount'],$param['reasons'],$param['is_can_wholesale']);
//            var_dump($param);die;
            $rs = $this->edit($param);
            if($rs === false){
                $this->setError(-1,'商品入库失败');
                $this->rollback();
                return false;
            }
//            var_dump($rs);die;
            foreach($stocks as $key => $value){
                $stocks[$key]['source_stock_id'] = $value['p_s_id'];
                $stocks[$key]['stock'] = $value['number'];
                $stocks[$key]['product_id'] = $rs;
                unset($stocks[$key]['p_s_id'],$stocks[$key]['number']);
            }
            $stock_params = $stocks;
//            echo "<pre>";
//            var_dump($stock_params);die;
            $s_rs = $stockModel->saveAll($stock_params);
            if($s_rs === false){
                $this->setError(-1,'新规格批量入库失败');
                $this->rollback();
                return false;
            }
        } else {
            $stocks = array_column($stocks,null,'p_s_id');
//            var_dump($stocks);die;
            $where = [
                ['product_id','=',$product['product_id']],
                ['source_stock_id','<>',0],
            ];
            $stock_array = $stockModel->where($where)->column('*','source_stock_id');
//            以申购记录商品为主，返回申购商品中不不同以往申购商品的规格属性
            $insert_param = array_diff_key($stocks,$stock_array);

            $update_param = array_diff_key($stock_array,$insert_param);

            if(!empty($insert_param)){
                foreach($insert_param as $key => $value){
                    $insert_param[$key]['source_stock_id'] = $value['p_s_id'];
                    $insert_param[$key]['stock'] = $value['number'];
                    $insert_param[$key]['product_id'] = $product['product_id'];
                    unset($insert_param[$key]['p_s_id'],$insert_param[$key]['number']);
                }
                $rs = $stockModel->saveAll($insert_param);
                if($rs === false){
                    $this->setError(-1,'新规格入库失败');
                    $this->rollback();
                    return false;
                }
            }
            if(!empty($update_param)){
                foreach($update_param as $key => $value){
                    $update_param[$key]['stock'] += $stocks[$key]['number'];
                    $update_param[$key]['is_del'] = 1;
                }
                $rs = $stockModel->saveAll($update_param);
                if($rs === false){
                    $this->setError(-1,'更新已有库存失败');
                    $this->rollback();
                    return false;
                }
            }
        }
        $this->commit();
        return true;
    }
}